<?php

/*
 * core/user.php
 *
 * provide common user methods
 *
 */

require_once( 'database_fct.php' );

class User
{
	/*
	 * getInfo()
	 * param: user: id or username
	 * return array of user info or null on error
	 */
	public static function getInfo( $user )
	{
		if( is_null($u = CoreDBFct::getUser( $user )) )
		{
			Log::error( 'unable to retreive user information for "'.$user.'"' );
			return null;
		}

		return $u;
	}

	/*
	 * addUser()
	 * return newly added user id or null on error
	 */
	public static function add( $username, $password, $email )
	{
		if( CoreDBFct::getUserId( $username ) != -1 )
		{
			Log::error( 'user "'.$username.'" already exist' );
			return null;
		}

		$id = CoreDBFct::insertUser( $username, $password, $email );
		if( $id == -1 )
		{
			Log::error( 'unable to insert user "'.$username.'"' );
			return null;
		}

		return $id;
	}

	/*
	 * removeUser()
	 * param: user: username or userid
	 * return: true/false
	 */
	public static function remove( $user )
	{
		if( is_null($u = CoreDBFct::getUser($user)) )
		{
			Log::error( 'user "'.$user.'" does not exist.' );
			return false;
		}

		if( !CoreDBFct::removeUser( $u['username'] ) )
		{
			Log::error( 'unable to remove user "'.$user.'"' );
			return false;
		}

		return true;
	}

	/*
	 * updateUser()
	 * param: email: optional
	 * return: true/false
	 */
	public static function update( $username, $password, $email=null )
	{
		if( CoreDBFct::getUserId($username) == -1 )
		{
			Log::error( 'user "'.$username.'" does not exist.' );
			return false;
		}

		if( !CoreDBFct::updateUser( $username, $password, $email ) )
		{
			Log::error( 'unable to update user "'.$username.'"' );
			return false;
		}

		return true;
	}

	/*
	 * listUsers()
	 * return: array
	 */
	public static function listUsers()
	{
		if( is_null($l = CoreDBFct::listUsers()) )
		{
			Log::error( 'unable to list users.' );
			return null;
		}

		return $l;
	}
}

?>
